<script setup lang="ts">
import dayjs from "dayjs";
import {useRoute} from "vue-router";
import {onMounted, ref} from "vue";
import {useGetOneByIdAPI} from "@/apis/material.js";
import {useGetMaterialInListByMaterialId, useGetMaterialInListCountsByMaterialId} from "@/apis/materialIn.js";
import {getProjectListAPI} from "@/apis/projectInfo.js";
import router from "@/router/index.js";
import {useGetMaterialOutListByMaterialId, useGetMaterialOutListCountsByMaterialId} from "@/apis/materialOut.js";

interface MaterialObject {
  id:number;
  materialName:string;
  typeName:string;
  brand:string;
  layout:string;
  pieces:string;
  number:number;
  stockTakeNumber:number;
  description:string;
  model:string;
}

interface MaterialIn{
  id:number;

  materialId:number;

  materialName:string;

  typeName:string;

  layout:string;

  brand:string;

  model:string;

  number:number;

  price:number;

  totalPrice:number;

  originNumber:number;

  encode:string;

  pieces:string;

  warehouse:string;

  receiveProject:string;

  description:string;

  createBy:string;

  lastUpdateBy:string;
}

interface MaterialOut{

  id:number;

  materialId:number;

  layout:string;

  materialName:string;

  typeName:string;

  brand:string;

  number:number;

  originNumber:number;

  recipient:string;

  pieces:string;

  model:string;

  encode:string;

  warehouse:string;

  receiveProject:string;

  description:string;

  createBy:string;

  lastUpdateBy:string;
}

interface ProjectInfo{
  id:number;

  name:string;

  contact:string;

  phone:string;

  address:string;

  description:string;
}


const route=useRoute();
const materialId=route.params.id;

const materialObj=ref<MaterialObject>({
  id:0,
  materialName:'',
  typeName:'',
  brand:'',
  layout:'',
  pieces:'',
  number:0,
  stockTakeNumber:0,
  description:'',
  model:''
})
const projectList=ref<ProjectInfo[]>([]);
const projectInfoIn=ref<ProjectInfo>({
  id:0,
  name:'',
  contact:'',
  phone:'',
  address:'',
  description:'',
});
const projectInfoOut=ref<ProjectInfo>({
  id:0,
  name:'',
  contact:'',
  phone:'',
  address:'',
  description:'',
});

// 分页显示数据
const currentIn=ref(1);
const currentOut=ref(1);
const pageSizeIn=ref(5);
const pageSizeOut=ref(5);

const startIn=ref('');
const startOut=ref('');
const endIn=ref('');
const endOut=ref('');

const projectNameIn=ref('');
const projectNameOut=ref('');

const materialInList=ref<MaterialIn[]>([]);
const materialInCounts=ref(0)
const materialOutList=ref<MaterialOut[]>([]);
const materialOutCounts=ref(0)

const allNumberIn=ref(0);
const totalPriceIn=ref(0);

const getNumberTotalPriceIn=()=>{
  allNumberIn.value=0;
  totalPriceIn.value=0;

  if (materialInList.value.length===0){
    allNumberIn.value=0;
    totalPriceIn.value=0;
  }
  else {
    materialInList.value.map((item:MaterialIn)=>{
      allNumberIn.value+=item.number;
      totalPriceIn.value+=item.totalPrice;
    })
  }
}

const allNumberOut=ref(0);


const recipient=ref('');



const getNumberTotalPriceOut=()=>{
  allNumberOut.value=0;

  if (materialOutList.value.length===0){
    allNumberOut.value=0;
  }
  else {
    materialOutList.value.map(item=>{
      allNumberOut.value+=item.number;
    })
  }
}


// 统一封装一个函数，用于获取materialInList的值
const getMaterialInList=async ()=>{
  const resMaterialIn=await useGetMaterialInListByMaterialId(timeInStatus.value, materialObj.value.id,currentIn.value,pageSizeIn.value,projectNameIn.value,startDateIn.value,endDateIn.value)
  materialInList.value=resMaterialIn.data;
  getNumberTotalPriceIn();
  const resMaterialInCount=await useGetMaterialInListCountsByMaterialId(timeInStatus.value,materialObj.value.id,projectNameIn.value,startDateIn.value,endDateIn.value)
  materialInCounts.value=resMaterialInCount.data;
}

// 统一封装一个函数，用于获取materialOutList的值
const getMaterialOutList=async ()=>{
  const resMaterialOut=await useGetMaterialOutListByMaterialId(timeOutStatus.value,materialObj.value.id,currentOut.value,pageSizeOut.value,projectNameOut.value,recipient.value,startDateOut.value,endDateOut.value)
  materialOutList.value=resMaterialOut.data;
  getNumberTotalPriceOut()
  const resMaterialOutCount=await useGetMaterialOutListCountsByMaterialId(timeOutStatus.value,materialObj.value.id,projectNameOut.value,recipient.value,startDateOut.value,endDateOut.value)
  materialOutCounts.value=resMaterialOutCount.data;
}


onMounted( async ()=>{
  const res=  await useGetOneByIdAPI(materialId);
  materialObj.value=res.data;
  const resProject=await getProjectListAPI(1,1000);
  projectList.value=resProject.data;
  await getMaterialInList();
  await getMaterialOutList();
})


const timeInStatus=ref(false);
const timeOutStatus=ref(false);


const dateValueIn = ref('')
const dateValueOut = ref('')
const options = [
  {
    value: 'todayDate',
    label: '今天',
  },
  {
    value: 'thisWeekDate',
    label: '7天内',
  },
  {
    value: 'thisMonthDate',
    label: '30日内',
  },
  {
    value: 'thisSeasonDate',
    label: '90日内',
  },
  {
    value: 'thisYearDate',
    label: '365日内',
  },
  {
    value: 'customDate',
    label: '自定义',
  },
]
// 时间选择器中，开始、结束时间
const startDateIn=ref<any>(new Date());
const startDateOut=ref<any>(new Date());
const endDateIn=ref<any>(new Date());
const endDateOut=ref<any>(new Date());

// 通过时间选择器选择时间
const dateTimeIn=ref<any>([]);
const dateTimeOut=ref<any>([]);
const dateOneIn=ref(Date);
const dateOneOut=ref(Date);
const dateTwoIn=ref(Date);
const dateTwoOut=ref(Date);


const timePickerDisableIn=ref(false);

const getMaterialInListByDatePickerIn=async ()=>{
  timeInStatus.value=true;
  dateOneIn.value=dateTimeIn.value[0];
  dateTwoIn.value=dateTimeIn.value[1];
  startDateIn.value=dateTimeIn.value[0];
  endDateIn.value=dateTimeIn.value[1];
  // 最后一天，他的时间是最后一天日期的0：00,所以必须要加上一天24*1000*3600
  endDateIn.value.setTime(endDateIn.value.getTime()+3600*1000*24);
  await  getMaterialInList();
}

const timePickerDisableOut=ref(false);

const getMaterialOutListByDatePicker=async ()=>{
  timeOutStatus.value=true;
  dateOneOut.value=dateTimeOut.value[0];
  dateTwoOut.value=dateTimeOut.value[1];
  startDateOut.value=dateTimeOut.value[0];
  endDateOut.value=dateTimeOut.value[1];
  // 最后一天，他的时间是最后一天日期的0：00,所以必须要加上一天24*1000*3600
  endDateOut.value.setTime(endDateOut.value.getTime()+3600*1000*24);
  await  getMaterialOutList();
}


const getMaterialInFormListByChooseTime=async ()=>{

  timeInStatus.value=true;

  materialInList.value.length=0;
  materialInCounts.value=0;
  if (dateValueIn.value==='todayDate'){
    startDateIn.value=new Date(dayjs().add(0, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateIn.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialInList();
  }
  if (dateValueIn.value==='thisWeekDate'){
    startDateIn.value=new Date(dayjs().add(-7, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateIn.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialInList();

  }
  if (dateValueIn.value==='thisMonthDate'){
    startDateIn.value=new Date(dayjs().add(-30, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateIn.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialInList();

  }
  if (dateValueIn.value==='thisSeasonDate'){
    startDateIn.value=dayjs().add(-90, 'd').startOf('day').format('YYYY-MM-DD');
    endDateIn.value= dayjs().format('YYYY-MM-DD');
    await getMaterialInList();
  }
  if (dateValueIn.value==='thisYearDate'){
    startDateIn.value=new Date(dayjs().add(-365, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateIn.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialInList();
  }
  if (dateValueIn.value=='customDate'){
    timePickerDisableIn.value=true;
  }
}

const getMaterialOutFormListByChooseTime=async ()=>{

  timeOutStatus.value=true;

  materialOutList.value.length=0;
  materialOutCounts.value=0;

  if (dateValueOut.value==='todayDate'){

    startDateOut.value=new Date(dayjs().add(0, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateOut.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialOutList();
  }
  if (dateValueOut.value==='thisWeekDate'){
    startDateOut.value=new Date(dayjs().add(-7, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateOut.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialOutList();
  }
  if (dateValueOut.value==='thisMonthDate'){
    startDateOut.value=new Date(dayjs().add(-30, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateOut.value=new Date(dayjs().format('YYYY-MM-DD'));
    await getMaterialOutList();

  }
  if (dateValueOut.value==='thisSeasonDate'){
    startDateOut.value=dayjs().add(-90, 'd').startOf('day').format('YYYY-MM-DD');
    endDateOut.value= dayjs().format('YYYY-MM-DD');
    await  getMaterialOutList();
  }
  if (dateValueOut.value==='thisYearDate'){
    startDateOut.value=new Date(dayjs().add(-365, 'd').startOf('day').format('YYYY-MM-DD'));
    endDateOut.value=new Date(dayjs().format('YYYY-MM-DD'));

    await getMaterialOutList();
  }
  if (dateValueOut.value=='customDate'){
    timePickerDisableOut.value=true;
  }
}


// 分页组件的每页条数值改变
const handleSizeChangeIn=async (val:any)=>{
  pageSizeIn.value=val;
  const res= await useGetMaterialInListByMaterialId(timeInStatus.value,materialObj.value.id,currentIn.value,pageSizeIn.value,projectNameIn.value,startDateIn.value,endDateIn.value);
  materialInList.value=res.data;
  getNumberTotalPriceIn();
}
const handleSizeChangeOut=async (val:any)=>{
  pageSizeOut.value=val;
  const res= await useGetMaterialOutListByMaterialId(timeOutStatus.value,materialObj.value.id,currentOut.value,pageSizeOut.value,projectNameOut.value,recipient.value,startDateOut.value,endDateOut.value);
  materialOutList.value=res.data;
  getNumberTotalPriceOut()

}
// 分页组件的第几页数值改变
const handleCurrentChangeIn=async (val:any)=>{
  currentIn.value=val;
  const res= await useGetMaterialInListByMaterialId(timeInStatus.value,materialObj.value.id,currentIn.value,pageSizeIn.value,projectNameIn.value,startDateIn.value,endDateIn.value);
  materialInList.value=res.data;
  getNumberTotalPriceIn();
}
const handleCurrentChangeOut=async (val:any)=>{
  currentOut.value=val;
  const res= await useGetMaterialOutListByMaterialId(timeOutStatus.value,materialObj.value.id,currentOut.value,pageSizeOut.value,projectNameOut.value,recipient.value,startDateOut.value,endDateOut.value);
  materialOutList.value=res.data;
  getNumberTotalPriceOut()
}

const originProjectChangeIn=async (val:any)=>{
  projectNameIn.value=val;
  await getMaterialInList();
}

const reloadFullListIn=async ()=>{
  await getMaterialInList();
}

const timeReloadFullListIn=async ()=>{
  timeInStatus.value=false;
  await reloadFullListIn();
}


const originProjectChangeOut=async (val:any)=>{
  projectNameOut.value=val;
  await getMaterialOutList();
}

const reloadFullListOut=async ()=>{
  currentOut.value=1;
  pageSizeOut.value=5;
 await getMaterialOutList();
}

const timeReloadFullListOut=()=>{
  timeOutStatus.value=false;
  reloadFullListOut();
}



const reloadFullListOutRecipient=async ()=>{
  recipient.value='';
  await reloadFullListOut();
}




const getByRecipient=async ()=>{
  await getMaterialOutList();
}


</script>

<template>
  <!-- 面包屑 -->
  <div style="padding-top: 5px;padding-left: 10px;padding-bottom: 5px">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/material`}" >材料主页</el-breadcrumb-item>
      <el-breadcrumb-item  >材料进出场统计</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <h3 style="padding-top: 10px;padding-bottom: 10px;padding-left: 20px">材料进场统计</h3>

  <!--这里放置各种查询组件  -->
  <div class="demo-date-picker">
    <span style="padding-left: 10px">材料来源地：</span><span  class="block">
      <!--  多种类型名称查询-->
      <el-select
          v-model="projectInfoIn"
          clearable
          placeholder="请选择材料来源地"
          style="width: 240px;"
          size="small"
          @change="originProjectChangeIn"
          @clear="reloadFullListIn"

      >
    <el-option
        v-for="item in projectList"
        :key="item.value"
        :label="item.name"
        :value="item.name"
    />
  </el-select>

  <span style="padding-left: 20px">进场时间：</span>
    <el-select
        v-model="dateValueIn"
        clearable
        placeholder="Select"
        style="width: 240px;"
        size="small"
        @change="getMaterialInFormListByChooseTime"
        @clear="timeReloadFullListIn"
    >
    <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    />
  </el-select>
    </span>
    <el-dialog title="请选择时间" width="450"  v-model="timePickerDisableIn" >
      <el-date-picker
          v-model="dateTimeIn"
          type="daterange"
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
          :size="'small'"
          @change="getMaterialInListByDatePickerIn"
      />
    </el-dialog>

  </div>


  <div class="table_contain">
    <div  class="block" style="float: right;padding-bottom: 20px">
      <el-pagination v-model:currentPage="currentIn"
                     :page-sizes="[10,15,30]"
                     :page-size="pageSizeIn" layout="total, sizes, prev, pager, next, jumper"
                     :total="materialInCounts"
                     @size-change="handleSizeChangeIn"
                     @current-change="handleCurrentChangeIn"
                     small
                     background
      >
      </el-pagination>
    </div>

    <!-- 对表格中的字段排序，在表格属性中添加:default-sort,后面参数是需要排序的字段，
         order:后面是排序要求,这里是descending,然后在需要排序的列元素中添加sortable属性-->
    <div style="margin-left: 0;padding-left: 0;width: 100%">
      <el-table
          :data="materialInList"
          style="width: 100%;margin-left: 0"
          stripe
          border
          max-height="780"
          :default-sort="{prop:'updateTime',order:'descending',}"
      >
        <el-table-column align="center" prop="materialName" fixed label="材料名称"  width="220" />

        <el-table-column align="center"  prop="brand" label="品牌" width="100" />

        <el-table-column align="center"  prop="model" label="型号" width="120" />

        <el-table-column align="center"  prop="pieces" label="单位" width="80" />

        <el-table-column align="center"  prop="number" label="数量" width="80"/>

        <el-table-column align="center"  prop="price" label="单价（元）" width="90"/>
        <el-table-column align="center"  prop="totalPrice" label="总价（元）" width="90"/>

        <el-table-column align="center"  prop="typeName" label="设备类型" width="130"/>

        <!--        <el-table-column prop="encode"  label="表单编号" width="255"    sortable />-->

        <!--        <el-table-column align="center"  prop="warehouse" label="材料所在仓库" width="150"/>-->

        <el-table-column align="center"  prop="receiveProject" label="材料来源地" width="150"/>
        <el-table-column align="center"  prop="layout" label="货架号" width="120"/>

        <!--        <el-table-column align="center" prop="createBy" label="操作人" width="150"/>-->

        <!--        <el-table-column prop="receivingProject" label="设备转场目的地" width="200"/>-->

        <el-table-column align="left"  prop="description" label="备注"  width="300"/>

        <el-table-column  label="操作" width="100" fixed="right">
          <!--  在操作这一栏，添加一个template元素，加一个#default属性，通过这个属性，获取到这一行的数据，是个对象
                       scope：就是el-table表格中被选中的那一行的数据，通过scope获取到该行的数据-->
          <template #default="scope">
            <el-button size="small" type="warning" plain  @click="router.push({path:`/home/material/materialInDetail/${scope.row.id}`})">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <h3 style="margin-left: 25px;padding-left: 20px;padding-top: 10px">总数量： {{allNumberIn}}{{materialObj.pieces}} ， 总价格：{{totalPriceIn}}元</h3>
  <hr style="padding-top: 20px;padding-top:  10px">



  <!-- ============================= 出场部分========================== -->
  <h3 style="padding-top: 10px;padding-bottom: 10px;padding-left: 20px">材料出场统计</h3>

  <!--这里放置各种查询组件  -->
  <div class="demo-date-picker">
    <span style="padding-left: 10px">材料接收地：</span><span  class="block">
      <!--  多种类型名称查询-->
      <el-select
          v-model="projectInfoOut"
          clearable
          placeholder="材料接收地"
          style="width: 240px;"
          size="small"
          @change="originProjectChangeOut"
          @clear="reloadFullListOut"
      >
    <el-option
        v-for="item in projectList"
        :key="item.value"
        :label="item.name"
        :value="item.name"
    />
  </el-select>

  <span style="padding-left: 20px">出场时间：</span>
    <el-select
        v-model="dateValueOut"
        clearable
        placeholder="Select"
        style="width: 240px;"
        size="small"
        @change="getMaterialOutFormListByChooseTime"
        @clear="timeReloadFullListOut"
    >
    <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    />
  </el-select>

    </span>
    <el-dialog title="请选择时间" width="450" v-model="timePickerDisableOut"  >
      <el-date-picker
          v-model="dateTimeOut"
          type="daterange"
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
          :size="'small'"
          @change="getMaterialOutListByDatePicker"
      />
    </el-dialog>

    <span style="padding-left: 20px">领取人：</span>   <el-input v-model="recipient" clearable style="width: 250px;height: 25px" placeholder="请输入领取人（需完全匹配）" @clear="reloadFullListOutRecipient" @blur="getByRecipient"  />&nbsp;

    <!--    <el-button @click="getByRecipient" >点击</el-button>-->
  </div>


  <div class="table_contain">
    <div  class="block" style="float: right;padding-bottom: 20px">
      <el-pagination v-model:currentPage="currentOut"
                     :page-sizes="[10,15,30]"
                     :page-size="pageSizeOut" layout="total, sizes, prev, pager, next, jumper"
                     :total="materialOutCounts"
                     @size-change="handleSizeChangeOut"
                     @current-change="handleCurrentChangeOut"
                     small
                     background
      >
      </el-pagination>
    </div>

    <!-- 对表格中的字段排序，在表格属性中添加:default-sort,后面参数是需要排序的字段，
         order:后面是排序要求,这里是descending,然后在需要排序的列元素中添加sortable属性-->
    <div style="margin-left: 0;padding-left: 0;width: 100%">
      <el-table
          :data="materialOutList"
          style="width: 100%;margin-left: 0"
          stripe
          border
          max-height="780"
          :default-sort="{prop:'updateTime',order:'descending',}"
      >
        <el-table-column align="center" prop="materialName" fixed label="材料名称"  width="220" />

        <el-table-column align="center"  prop="brand" label="品牌" width="100" />

        <el-table-column align="center"  prop="model" label="型号" width="120" />

        <el-table-column align="center"  prop="pieces" label="单位" width="80" />

        <el-table-column align="center"  prop="number" label="数量" width="80"/>

        <el-table-column align="center"  prop="typeName" label="设备类型" width="130"/>

        <!--        <el-table-column align="center"  prop="warehouse" label="材料所在仓库" width="150"/>-->

        <el-table-column align="center"  prop="receiveProject" label="材料接收地" width="180"/>
        <el-table-column align="center"  prop="recipient" label="领取人" width="150"/>
        <el-table-column align="center"  prop="layout" label="货架号" width="120"/>

        <el-table-column align="left"  prop="description" label="备注"  width="300"/>

        <el-table-column  label="操作" width="100" fixed="right">
          <!--  在操作这一栏，添加一个template元素，加一个#default属性，通过这个属性，获取到这一行的数据，是个对象
                       scope：就是el-table表格中被选中的那一行的数据，通过scope获取到该行的数据-->
          <template #default="scope">
            <el-button size="small" type="warning" plain  @click="router.push({path:`/home/material/materialOutDetail/${scope.row.id}`})">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <h3 style="margin-left: 25px;padding-left: 20px;padding-top: 10px">总数量：{{allNumberOut}}{{materialObj.pieces}}</h3>

  </div>
</template>

<style scoped lang="scss">

</style>